package com.liuyi.netty.im.test.lychat.im;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.TokenSign;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.liuyi.netty.im.server.handle.service.RelationChainService;
import com.liuyi.netty.im.server.handle.service.model.UserAuthResult;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 关系链 实现
 *
 * @author Mr.Fmy
 * @since 2021/12/25
 */
@Service
public class LychatRelationChainService implements RelationChainService {

    @Override
    public UserAuthResult login(String sign) {
        Object userId = StpUtil.getLoginIdByToken(sign);
        if (userId == null) {
            return null;
        }

        final UserAuthResult userAuthResult = new UserAuthResult();
        userAuthResult.setUserId(userId.toString());
        SaSession session = StpUtil.getSessionByLoginId(userId, false);
        if (session != null) {
            List<TokenSign> tokenSignList = session.getTokenSignList();
            for (TokenSign tokenSign : tokenSignList) {
                if (tokenSign.getValue().equals(sign)) {
                    userAuthResult.setDevice(tokenSign.getDevice());
                }
            }
        }
        if (StrUtil.isEmpty(userAuthResult.getDevice()) || StrUtil.isEmpty(userAuthResult.getUserId())) {
            return null;
        }
        return userAuthResult;
    }

    @Override
    public void logout(String sign) {
        StpUtil.logoutByTokenValue(sign);
    }

    @Override
    public void replaced(String sign) {
    }

    @Override
    public Object c2cProfile(String userId, String fiendUserId) {
        SaSession session = StpUtil.getSessionByLoginId(userId, false);
        if (session != null) {
            return session.getDataMap();
        }
        return null;
    }

    @Override
    public Object groupProfile(String userId, String groupId) {
        SaSession session = StpUtil.getSessionByLoginId(userId, false);
        if (session != null) {
            return session.getDataMap();
        }
        return null;
    }

    @Override
    public List<String> listByGroupIdManage(String groupId) {
        return new ArrayList<>();
    }

    @Override
    public List<String> listByGroupId(String groupId) {
        return new ArrayList<>();
    }
}
